import { resolve } from 'node:path'

import { customHtml } from '@ttou/vite-html'
import legacy from '@vitejs/plugin-legacy'
import react from '@vitejs/plugin-react-swc'
import autoprefixer from 'autoprefixer'
import postcssMobileForever from 'postcss-mobile-forever'
import postcssNested from 'postcss-nested'
import imagemin from 'unplugin-imagemin/vite'
import { CommonServerOptions, defineConfig, loadEnv } from 'vite'
import { analyzer } from 'vite-bundle-analyzer'

import { browserslist } from './package.json'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, '.')
  const commonServerOptions: CommonServerOptions = {
    host: true,
    open: true,
    port: 8080
  }

  return {
    css: {
      modules: {
        generateScopedName: '[local]__[hash:base64:5]'
      },
      postcss: {
        plugins: [
          autoprefixer(),
          postcssMobileForever({
            appSelector: '#root',
            unitPrecision: Number(env.VITE_APP_DESIGN_UNIT_PRECISION),
            viewportWidth: Number(env.VITE_APP_DESIGN_WIDTH),
            maxDisplayWidth: 600,
            landscapeWidth: 450,
            border: '#ebedf0',
            disableDesktop: true,
            disableLandscape: true,
            rootContainingBlockSelectorList: ['adm-popup']
          }),
          postcssNested({ preserveEmpty: true })
        ]
      }
    },
    resolve: {
      alias: [
        {
          find: '@/',
          replacement: `${resolve(__dirname, 'src')}/`
        }
      ]
    },
    plugins: [
      react(),
      legacy({
        targets: browserslist
      }),
      customHtml({
        injectVer: `<meta name="version-no" content="${new Date().getTime()}"/>`,
        injectTitle: `<title>${env.VITE_APP_TITLE}</title>`
      }),
      imagemin({
        mode: 'sharp',
        beforeBundle: true
      }),
      ...(mode === 'analyzer' ? [analyzer()] : [])
    ],
    optimizeDeps: {
      include: ['dayjs/locale/zh-cn']
    },
    build: {
      cssTarget: ['chrome61'],
      chunkSizeWarningLimit: 1024,
      reportCompressedSize: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            react: ['react', 'react-dom', 'react-router-dom', 'zustand'],
            'antd-mobile': ['antd-mobile'],
            iconify: ['@iconify/react']
          }
        }
      }
    },
    server: {
      ...commonServerOptions
    },
    preview: {
      ...commonServerOptions
    }
  }
})
